# mcp_tools.py
import requests
import json
from datetime import datetime
import os

class MCPWeatherTool:
    """天气查询工具 - MCP协议实现"""
    
    def __init__(self, api_key=None):
        self.api_key = api_key or os.getenv("OPENWEATHER_API_KEY")
        self.base_url = "http://api.openweathermap.org/data/2.5/weather"
    
    def get_weather(self, location: str) -> dict:
        """获取指定位置的天气信息"""
        try:
            params = {
                'q': location,
                'appid': self.api_key,
                'units': 'metric',
                'lang': 'zh_cn'
            }
            response = requests.get(self.base_url, params=params)
            data = response.json()
            
            if response.status_code == 200:
                return {
                    'location': location,
                    'temperature': data['main']['temp'],
                    'humidity': data['main']['humidity'],
                    'description': data['weather'][0]['description'],
                    'success': True
                }
            else:
                return {'error': data.get('message', '天气查询失败'), 'success': False}
        except Exception as e:
            return {'error': str(e), 'success': False}

class MCPCalculatorTool:
    """数学计算工具 - MCP协议实现"""
    
    def calculate(self, expression: str) -> dict:
        """执行数学计算"""
        try:
            # 安全评估数学表达式
            allowed_chars = set('0123456789+-*/.() ')
            if all(c in allowed_chars for c in expression):
                result = eval(expression)
                return {'expression': expression, 'result': result, 'success': True}
            else:
                return {'error': '表达式包含不安全字符', 'success': False}
        except Exception as e:
            return {'error': f'计算错误: {str(e)}', 'success': False}


class MCPFileTool:
    """文件操作工具 - MCP协议实现"""
    
    def read_file(self, filepath: str) -> dict:
        """读取文件内容"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                content = f.read()
            return {'filepath': filepath, 'content': content, 'success': True}
        except Exception as e:
            return {'error': str(e), 'success': False}
    
    def write_file(self, filepath: str, content: str) -> dict:
        """写入文件内容"""
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            return {'filepath': filepath, 'success': True}
        except Exception as e:
            return {'error': str(e), 'success': False}